import { Empty, Message, Table } from '@arco-design/web-react';
import DetailModal from '@src/components/detailModal';
import LoadingMask from '@src/components/loadingMask';
import { AppStore } from '@src/types';
import usePageUtils from '@src/utils/pageUtils';
import React, { useEffect, useState } from 'react';
import { shallowEqual, useSelector } from 'react-redux';
import { apiImportGenTable } from '../api';
import { Gen } from '../types';
interface Props {
  onClose: (update?: boolean) => void;
}
export default function ImportDBDialog({ onClose }: Props) {
  const pageUtils = usePageUtils({ model: 'code', table: 'gen', path: 'db/list', type: 'paginate' });

  // 当前页面选中的数据列表
  const [tabSelectRows, setTabSelectRows] = useState<Gen[]>([]);

  // 当前页需要的数据
  const list = useSelector((state: AppStore) => state.paginate[pageUtils.stateKey], shallowEqual);

  function createParams() {
    return {};
  }

  // 需要随时刷新 创建参数的方法
  useEffect(() => {
    pageUtils.setFun(createParams);
  }, [createParams]); // eslint-disable-line

  useEffect(() => {
    pageUtils.handleRefreshData();
  }, []); // eslint-disable-line

  // 列表项有选择变动
  function handleTabSelectChange(selectedRowKeys: React.Key[], selectedRows: Gen[]) {
    setTabSelectRows(selectedRows);
  }

  // 导入
  async function handleConfirm() {
    if (tabSelectRows.length <= 0) {
      onClose();
    } else {
      LoadingMask.show('正在导入...');
      try {
        let res = await apiImportGenTable(tabSelectRows.map((i) => i.tableName!).join(','));
        let data = res.data;
        if (data.code === 200) {
          Message.success('导入成功');
          onClose(true);
        } else {
          Message.warning(data.msg ?? '导入失败');
          onClose();
        }
      } catch (e: any) {
        Message.error(e.message ?? '导入失败');
        onClose();
      } finally {
        LoadingMask.hide();
      }
    }
  }

  let dataSource: Gen[] = list?.results || [];
  dataSource = dataSource.map((item) => Object.assign({}, item, { key: item.tableName! }));
  // 定义表格内的列
  const columns = [
    {
      title: '表名',
      dataIndex: 'tableName',
      key: 'tableName',
    },
    {
      title: '表描述',
      dataIndex: 'tableComment',
      key: 'tableComment',
    },

    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
  ];
  return (
    <DetailModal title="导入表" show className="w-700" onConfirm={() => handleConfirm()} onCancel={() => onClose()}>
      <Table
        className="table bw-100"
        rowSelection={{ type: 'checkbox', onChange: handleTabSelectChange }}
        data={dataSource}
        columns={columns}
        pagination={{
          className: 'pagination-block',
          total: list?.total || 1,
          current: pageUtils.pageNum,
          pageSize: pageUtils.pageSize,
          showJumper: true,
          sizeOptions: pageUtils.defaultPageSizeOptions,
          showTotal: (total) => '共' + total + '条',
          size: 'small',
          onChange: pageUtils.handlePageAndSizeChange,
        }}
        noDataElement={<Empty description={list?.error ?? '暂无数据'} />}
        loading={!list || (list?.fetching && !list?.loaded)}
      />
    </DetailModal>
  );
}
